package com.sky.service.admin.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.mapper.user.UserDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserDishMapper userDishMapper;
    //本质是两张表 ，1.dish 2.dish_flavor
    //现存dish表，然后把或得到的dish表的id赋值给flavor里面
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)){
            for (DishFlavor flavor : flavors){
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);//后绪步骤实现
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Transactional//事务
    public void deleteBatch(List<Long> ids) {
        //查询删除的菜品是否有在起售中的
        Integer count = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if(count>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //查询删除的菜品是否有被套餐关联的
        Integer count2= setmealDishMapper.selectCountByDishIds(ids);
        if(count2>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //都没有，删除菜品的口味信息
        dishFlavorMapper.deleteByDishIds(ids);

        //删除菜品信息
        dishMapper.deleteByIds(ids);
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishVO =  dishMapper.selectById(id);

        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //        1.修改dish表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
//        2.修改dish_flavor表(对于关系表的修改操作)
//        a.先删除原有数据
        dishFlavorMapper.deleteByDishId(dish.getId());
//        b.添加新的数据 -- 批量新增
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.batchSave(flavors);
        cleanCache();
    }

    /**
     * 通过id 查询分类下的菜品和口味
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> selectDishByCategoryId(Integer categoryId) {
        //在redis中构造key的规则
        String key = RedisConstant.CATEGORY_CACHE_PREFIX + categoryId;
        String dishJosn = (String)redisTemplate.opsForValue().get(key);
        if (StringUtils.hasText(dishJosn)){
            log.info("从缓存中查询，CatrgoryId :{}",categoryId);
            return JSONObject.parseArray(dishJosn,DishVO.class);
        }
        //List<Dish> dishList = userMapper.selectDishByCategoryId(categoryId);

        List<DishVO> list = userDishMapper.selectDishByCategoryId(categoryId);
        List<Long> dishIds = list.stream().map(DishVO::getId).collect(Collectors.toList());
        List<DishFlavor> dishFlavors = userDishMapper.selectDishFlavorbyCategoryIds(dishIds);



        log.info("list有值吗？值是多少？{}",list);
        List<DishVO> dishVOList = new ArrayList<>();
        for (DishVO dishVO : list) {
            DishVO dishVO1 = new DishVO();
            BeanUtils.copyProperties(dishVO ,dishVO1);
            List<DishFlavor> flavors = dishFlavors.stream().filter(f -> f.getDishId().equals(dishVO.getId())).collect(Collectors.toList());

            dishVO1.setFlavors(flavors);
            dishVOList.add(dishVO1);
        }

        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));
        return dishVOList;
    }

    private void cleanCache(){

        Set keys = redisTemplate.keys(RedisConstant.CATEGORY_CACHE_PREFIX+"*");
        redisTemplate.delete(keys);
    }
    //修改或者删除时，同时也清理掉缓存中的内容
    private void deleteCategoryCache(){
        //redis 的删除方法 key 就是分类的key
        redisTemplate.delete("CATEGORY_LIST");
    }
}
